package com.yuyou.activity.group.job.Async;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.yuyou.activity.comm.service.tool.MailUtil;
import com.yuyou.activity.group.service.entity.ActivityGroupbuy;
import com.yuyou.activity.group.service.entity.ActivityGroupbuyOrder;
import com.yuyou.activity.group.service.service.*;
import com.yuyou.activity.util.bean.ReturnResult;
import com.yuyou.activity.util.enums.*;
import com.yuyou.activity.util.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.yuyou.activity.comm.service.service.ISmsService;
import com.yuyou.activity.group.service.entity.ActivityGroupJob;
import com.yuyou.activity.group.service.entity.ActivityGroupUser;
import com.yuyou.activity.util.bean.MessageResult;
import com.yuyou.activity.util.util.SpringUtil;

import java.util.List;

/**
 * Create by chengsiyuan on 2018/12/03
 **/
@Component
public class AsyncService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISmsService smsService;

    @Autowired
    private IActivityGroupJobService activityGroupJobService;

    @Autowired
    private IActivityGroupUserService activityGroupUserService;

    @Autowired
    private IActivityGroupbuyOrderService activityGroupbuyOrderService;

    @Autowired
    private IActivityGroupSPService activityGroupSPService;

    @Autowired
    private IActivityGroupbuyOrderDetailService activityGroupbuyOrderDetailService;

    @Autowired
    private IActivityGroupbuyService activityGroupbuyService;

    @Autowired
    private MailUtil mailUtil;


    @Async("taskExecutor")
    public void AsyncSendMessageJob(ActivityGroupJob job){
        ActivityGroupUser user = activityGroupUserService.selectByPrimaryKey(job.getfId());
        if(user == null){
            activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , "activityUser找不到");
//            activityGroupUserService.udateStatus(user.getActivityGroupUserId() , ActivityGroupEnums.isNotice.fail.getValue());
            logger.error(Thread.currentThread().getName()+"-短信发送失败,查询activityUser-"+job.getfId()+"-找不到数据");
        }else {
            //调用发送短信
    		String mess=SmsGroupSuccMessEnums.Mess.getValByKey(user.getProjectCode());
        	
    		//测试环境配置
    		Environment env=(Environment)SpringUtil.getBean("environment");
    		String messageOpen=env.getProperty("message.open");
    		if(messageOpen.equals("off")){	
                //更新用户状态
                activityGroupUserService.udateStatus(user.getActivityGroupUserId() , ActivityGroupEnums.isNotice.success.getValue());
                //更新任务状态
                activityGroupJobService.updateJobStatus(job.getfId() ,
                        ActivityGroupJobEnums.type.GROUP.getValue() ,
                        ActivityGroupJobEnums.tag.GROUP.getValue() ,
                        ActivityGroupJobEnums.status.success.getValue(),
                        "test");
    		}else{
                MessageResult smsResult = smsService.sendCode(user.getPhone(), null, mess);
                String result = "";
                if(smsResult != null){
                    result = JSON.toJSONString(smsResult);
                }
                if(smsResult != null && smsResult.getResultCode() == 0){
                    //更新用户状态
                    activityGroupUserService.udateStatus(user.getActivityGroupUserId() , ActivityGroupEnums.isNotice.success.getValue());
                    //更新任务状态
                    activityGroupJobService.updateJobStatus(job.getfId() ,
                            ActivityGroupJobEnums.type.GROUP.getValue() ,
                            ActivityGroupJobEnums.tag.GROUP.getValue() ,
                            ActivityGroupJobEnums.status.success.getValue(),
                            result);
                }else{
                    //更新用户状态
                    activityGroupUserService.udateStatus(user.getActivityGroupUserId() , ActivityGroupEnums.isNotice.fail.getValue());
                    //更新任务状态
                    activityGroupJobService.updateJobStatus(job.getfId() ,
                            ActivityGroupJobEnums.type.GROUP.getValue() ,
                            ActivityGroupJobEnums.tag.GROUP.getValue() ,
                            ActivityGroupJobEnums.status.fail.getValue(),
                            result);
                }    			
    		}
    		
        }

    }

    @Async("taskExecutor")
    public void AsyncSHIPINJob(ActivityGroupJob job){
        ActivityGroupbuyOrder order = activityGroupbuyOrderService.selectByPrimaryKey(job.getfId());
        if(order == null){
            activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , "order找不到");
            logger.error(Thread.currentThread().getName()+"-短信发送失败,查询groupBuy_order-"+job.getfId()+"-找不到数据");
        }else {
            ActivityGroupbuy g = activityGroupbuyService.selectByPrimaryKey(order.getActivityGroupbuyId());
            if(g == null){
                activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , "activityGroupbuy找不到");
                logger.error(Thread.currentThread().getName()+"-短信发送失败,查询groupBuy-"+job.getfId()+"-找不到数据");
                return;
            }
            //调用发送短信,获取短信内容
            String mess = SmsGroupSPSuccMessEnums.Mess_type.getValByKey(order.getProjectCode() , g.getGroupType());

            //测试环境配置
            Environment env=(Environment)SpringUtil.getBean("environment");
            String messageOpen=env.getProperty("message.open");
            if(messageOpen.equals("off")){
                //更新用户状态
                activityGroupbuyOrderService.udateStatus(order.getActivityGroupbuyOrderId() , ActivityGroupEnums.isNotice.success.getValue());
                //更新任务状态
                activityGroupJobService.updateJobStatus(job.getfId() ,
                        ActivityGroupJobEnums.type.GROUP_SHIPIN.getValue() ,
                        ActivityGroupJobEnums.tag.GROUP_SHIPIN.getValue() ,
                        ActivityGroupJobEnums.status.success.getValue(),
                        "test");
            }else{
                MessageResult smsResult = smsService.sendCode(order.getPhone(), null, mess);
                String result = "";
                if(smsResult != null){
                    result = JSON.toJSONString(smsResult);
                }
                if(smsResult != null && smsResult.getResultCode() == 0){
                    //更新用户状态
                    activityGroupbuyOrderService.udateStatus(order.getActivityGroupbuyOrderId(), ActivityGroupEnums.isNotice.success.getValue());
                    //更新任务状态
                    activityGroupJobService.updateJobStatus(job.getfId() ,
                            ActivityGroupJobEnums.type.GROUP_SHIPIN.getValue() ,
                            ActivityGroupJobEnums.tag.GROUP_SHIPIN.getValue() ,
                            ActivityGroupJobEnums.status.success.getValue(),
                            result);
                }else{
                    //更新用户状态
                    activityGroupbuyOrderService.udateStatus(order.getActivityGroupbuyOrderId() , ActivityGroupEnums.isNotice.fail.getValue());
                    //更新任务状态
                    activityGroupJobService.updateJobStatus(job.getfId() ,
                            ActivityGroupJobEnums.type.GROUP_SHIPIN.getValue() ,
                            ActivityGroupJobEnums.tag.GROUP.GROUP_SHIPIN.getValue() ,
                            ActivityGroupJobEnums.status.fail.getValue(),
                            result);
                }
            }

        }
    }


    @Async("taskShiPinExecutor")
    public void AsyncShiPinComJob(ActivityGroupJob job){
        try {
            ActivityGroupbuyOrder order = activityGroupbuyOrderService.selectByPrimaryKey(job.getfId());
            if(order == null){
                activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , "order找不到");
                LogUtil.error(logger , Thread.currentThread().getName()+"-查询订单数据失败,查询groupBuy_order-"+job.getfId()+"-找不到数据");
            }else {
                List<Long> resourceList =  activityGroupbuyOrderDetailService.findSourceIdByOrderId(order.getActivityGroupbuyOrderId());
                if(resourceList.size() > 0 ){
                    String ids = "";
                    for (Long i :
                            resourceList) {
                        ids = ids + i + ",";
                    }
                    //同步至shipin.com
                    ReturnResult<String> result = activityGroupSPService.synchUserOrder2Shipin(order.getName() , order.getPhone() , ids.substring(0 , ids.length() -1));
                    if(result.isSuccess()){
                        LogUtil.info(logger , "同步至shipin.com成功");

                        
                        ActivityGroupbuyOrder updateOrder=new ActivityGroupbuyOrder();
                		updateOrder.setActivityGroupbuyOrderId(order.getActivityGroupbuyOrderId());
                		updateOrder.setIsSync(ActivityGroupBuyOrderEnums.isSync.SUCCESS.getValue());
                        activityGroupbuyOrderService.updateByPrimaryKeySelective(updateOrder);
                        
//                       order.setIsSync(ActivityGroupBuyOrderEnums.isSync.SUCCESS.getValue());                        
//                       activityGroupbuyOrderService.updateByPrimaryKeySelective(order);
                        
                        
                        activityGroupJobService.updateJob(ActivityGroupJobEnums.status.success.getValue() , job.getId() , result.getDesc());
                    }else {
                        LogUtil.warn(logger , "同步至shipin.com失败：" + result.getDesc());
                        mailUtil.sendEmail("sp" , ""+job.getfId());
                        
//                        order.setIsSync(ActivityGroupBuyOrderEnums.isSync.FAIL.getValue());
//                        activityGroupbuyOrderService.updateByPrimaryKeySelective(order);
 
                        ActivityGroupbuyOrder updateOrder=new ActivityGroupbuyOrder();
                		updateOrder.setActivityGroupbuyOrderId(order.getActivityGroupbuyOrderId());
                		updateOrder.setIsSync(ActivityGroupBuyOrderEnums.isSync.FAIL.getValue());
                        activityGroupbuyOrderService.updateByPrimaryKeySelective(updateOrder);
                        
                        activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , result.getDesc());
                    }

                }
            }
        } catch (Exception e) {
        	mailUtil.sendEmail("sp" , ""+job.getfId());
            activityGroupJobService.updateJob(ActivityGroupJobEnums.status.fail.getValue() , job.getId() , ExceptionUtil.getMessage(e));
            LogUtil.error(logger , e.getMessage());
        }
    }

    @Async("taskOrderExecutor")
    public void AsyncOrderCheck(Long activityGroupbuyOrderId){
        try {
            LogUtil.info(logger , "订单补偿，orderID：" + activityGroupbuyOrderId);
            activityGroupSPService.compensateOrder(activityGroupbuyOrderId);
        } catch (Exception e) {
            LogUtil.error(logger , ExceptionUtil.getMessage(e));
        }
    }
}
